package com.richest.api.utils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SSL请求工具类 基于httpclient-4.3.6.jar和httpcore-4.3.3.jar
 * 
 * @author 梁峰 2016-07-05
 */
public class SSLClientTool {
	private static Logger logger = LoggerFactory.getLogger(SSLClientTool.class);
	public static final int SO_TIMEOUT = 60000;
	public static final int CONN_TIMEOUT = 60000;
	public static PoolingHttpClientConnectionManager poolConnManager;

	static {
		SSLContext ctx = null;
		try {
			ctx = SSLContext.getInstance("TLSv1");
			ctx.init(null, new TrustManager[] { new TrustAnyTrustManager() }, null);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx,
				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

		// 使用连接池
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
		// 初始化连接管理器
		poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		// Increase max total connection to 200
		poolConnManager.setMaxTotal(200);
		// Increase default max connection per route to 20
		poolConnManager.setDefaultMaxPerRoute(20);
		SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(SO_TIMEOUT).build();
		poolConnManager.setDefaultSocketConfig(socketConfig);
	}

	public static CloseableHttpClient getSSLConnection() throws Exception {
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONN_TIMEOUT)
				.setConnectTimeout(CONN_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolConnManager)
				.setDefaultRequestConfig(requestConfig).build();
		if (poolConnManager != null && poolConnManager.getTotalStats() != null) {
			logger.info("now client pool " + poolConnManager.getTotalStats().toString());
		}
		return httpClient;
	}

}
